package com.chuzhiyun.chengguoxy.feature.internship.worktags;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.ServiceSettings;
import com.chuzhiyun.chengguoxy.R;
import com.chuzhiyun.chengguoxy.databinding.FragmentWorkTagsInputBinding;
import com.chuzhiyun.chengguoxy.feature.base.BaseFragment;
import com.chuzhiyun.chengguoxy.feature.bean.WorkTagsConfigBean;
import com.chuzhiyun.chengguoxy.network.NetApi;
import com.chuzhiyun.chengguoxy.network.NetService;
import com.chuzhiyun.chengguoxy.network.StringNetCallback;
import com.chuzhiyun.chengguoxy.utlis.CustomClickListener;
import com.chuzhiyun.chengguoxy.utlis.LocationUtils;
import com.chuzhiyun.chengguoxy.utlis.StringUtils;
import com.chuzhiyun.chengguoxy.utlis.TimeUtils;
import com.chuzhiyun.chengguoxy.utlis.ToastCustom;
import com.codingending.popuplayout.PopupLayout;
import com.google.gson.Gson;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class WorkTagsInputFragment extends BaseFragment<FragmentWorkTagsInputBinding> {

    private String tasksId;
    @SuppressWarnings("FieldCanBeLocal")
    private String tasksName;

    private  WorkTagsConfigBean configBean;
    private String titleValue;//标题
    private String dateValue;//日期
    private String textValue;//文本内容
    private String latitude;
    private String longitude;
    private String adminDivision;
    private String street;
    @SuppressWarnings("FieldMayBeFinal")
    private ArrayList<File> addFiles = new ArrayList<>();

    @Override
    public void initView(View view) {
        binding.navView.ivBack.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                requireActivity().finish();
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        Bundle bundle = getArguments();
        tasksId = bundle != null ? bundle.getString("tasksId") : null;
        System.out.println(tasksId);
        tasksName =  bundle != null ? bundle.getString("tasksName") : null;
        binding.navView.tvTitle.setText(tasksName);

        getWorkTags();
        initEditLength(binding.editLiyou,binding.tvLengthTip,500);
        binding.titleEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                titleValue = binding.titleEdit.getText().toString();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        binding.messageTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                textValue = binding.messageTitle.getText().toString();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        binding.xuanzeRl.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                showBottomTimeChoose();
            }
        });
        binding.refreshText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                getLocalInfo();
            }
        });

        binding.localBtn.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                getLocalInfo();
            }
        });
        binding.tvSubmit.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                submitClick();
            }
        });
    }

    private void getLocalInfo(){
        try {
            LocationUtils.getInstance().getLocation(getContext(), new LocationUtils.OnLocationChangedListener() {
                @SuppressLint("DefaultLocale")
                @Override
                public void onSuccess(AMapLocation amapLocation) {
                    street = amapLocation.getAoiName();
                    adminDivision = amapLocation.getAdCode();
                    longitude = String.format("%.6f",amapLocation.getLongitude());
                    latitude = String.format("%.6f",amapLocation.getLatitude());
                    binding.addressText.setText(street);
                    if (!StringUtils.isBlank(street)){
                        binding.localbtnLl.setVisibility(View.GONE);
                        binding.addressInfoRl.setVisibility(View.VISIBLE);
                    }
                    else {
                        binding.localbtnLl.setVisibility(View.VISIBLE);
                        binding.addressInfoRl.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onFail(int errCode, String errInfo) {
                    System.out.println(errCode);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showBottomTimeChoose(){

        //时间选择器
        View view=View.inflate(getContext(),R.layout.timechoose_menu,null);
        PopupLayout popupLayout = PopupLayout.init(getContext(),view);
        popupLayout.show();

        dateValue = TimeUtils.getCurrentTime();

        TextView monthText = view.findViewById(R.id.month_Text);
        CalendarView calendarView = view.findViewById(R.id.calendarView);
        ImageView calendarLeft = view.findViewById(R.id.left_Text);
        ImageView calendarRight = view.findViewById(R.id.right_Text);
        calendarLeft.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                calendarView.scrollToPre();
            }

        });
        calendarRight.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                calendarView.scrollToNext();
            }

        });

        calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                String dateStr = null;
                try {
                    dateStr = TimeUtils.strToDateFormat(calendar.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                dateValue = dateStr;
            }
        });

        java.util.Calendar calendar = java.util.Calendar.getInstance();
        int y = calendar.get(java.util.Calendar.YEAR);
        int m = calendar.get(java.util.Calendar.MONTH);

        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月");
        calendar.setTime(new Date());
        String monthString = df.format(calendar.getTime());
        monthText.setText(monthString);
        calendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() {
            @SuppressLint("DefaultLocale")
            @Override
            public void onMonthChange(int year, int month) {
                if (month<10)
                {
                    monthText.setText(String.format("%d年0%d月", year, month));
                }
                else
                {
                    monthText.setText(String.format("%d年%d月", year, month));
                }
            }
        });

        TextView cancelText = view.findViewById(R.id.cancel_Text);
        TextView sureText = view.findViewById(R.id.sure_Text);
        cancelText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                popupLayout.dismiss();
            }

        });
        sureText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                binding.chooseTime.setText(dateValue);
                popupLayout.dismiss();
            }
        });
    }


    private void getWorkTags(){
        String url = NetApi.getWorkTagsConfig(tasksId);
        NetService.getInstance().get(url, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                System.out.println(response);
                if (statusCode==200){
                    Gson gson = new Gson();
                    configBean = gson.fromJson(response, WorkTagsConfigBean.class);
                    setInputView();
                }
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
            }
        });
    }

    private void setInputView(){
        if (configBean.isEnableTitle()){
            binding.titleRl.setVisibility(View.VISIBLE);
            binding.line0.setVisibility(View.VISIBLE);
            if (configBean.isTitleRequired()){
                binding.titleRequiredRl.setVisibility(View.VISIBLE);
                binding.titleTv2.setVisibility(View.GONE);
            }
            else {
                binding.titleRequiredRl.setVisibility(View.GONE);
                binding.titleTv2.setVisibility(View.VISIBLE);
            }
        }
        else {
            binding.titleRl.setVisibility(View.GONE);
            binding.line0.setVisibility(View.GONE);
        }

        if (configBean.isEnableDate()){
            binding.dateRl.setVisibility(View.VISIBLE);
            binding.line1.setVisibility(View.VISIBLE);
            if (configBean.isDateRequired()){
                binding.dateRequiredRl.setVisibility(View.VISIBLE);
                binding.titleTv3.setVisibility(View.GONE);
            }
            else {
                binding.dateRequiredRl.setVisibility(View.GONE);
                binding.titleTv3.setVisibility(View.VISIBLE);
            }
        }
        else {
            binding.dateRl.setVisibility(View.GONE);
            binding.line1.setVisibility(View.GONE);
        }

        if (configBean.isEnableText()){
            binding.messageLl.setVisibility(View.VISIBLE);
            binding.line3.setVisibility(View.VISIBLE);
            if (configBean.isTextRequired()){
                binding.textRequiredRl.setVisibility(View.VISIBLE);
                binding.messageTitle.setVisibility(View.GONE);
            }
            else {
                binding.textRequiredRl.setVisibility(View.GONE);
                binding.messageTitle.setVisibility(View.VISIBLE);
            }
        }
        else {
            binding.messageLl.setVisibility(View.GONE);
            binding.line3.setVisibility(View.GONE);
        }

        if (configBean.isEnableFile()){
            binding.pictureLl.setVisibility(View.VISIBLE);
            if (configBean.isFileRequired()){
                binding.pictureRequiredRl.setVisibility(View.VISIBLE);
                binding.pictureTitleTv.setVisibility(View.GONE);
            }
            else {
                binding.pictureRequiredRl.setVisibility(View.GONE);
                binding.pictureTitleTv.setVisibility(View.VISIBLE);
            }
        }
        else {
            binding.pictureLl.setVisibility(View.GONE);
        }

        if (configBean.isEnablePosition()){
            binding.addressLl.setVisibility(View.VISIBLE);
            if (configBean.isPositionRequired()){
                binding.addressRequiredRl.setVisibility(View.VISIBLE);
                binding.addressTitleTv.setVisibility(View.GONE);
            }else {
                binding.addressRequiredRl.setVisibility(View.GONE);
                binding.addressTitleTv.setVisibility(View.VISIBLE);
            }
        }else {
            binding.addressLl.setVisibility(View.GONE);
        }

    }

    private void submitClick(){
        String url = NetApi.postTasksInfo();
        HashMap<String,String>param = new HashMap<>();
        if (!StringUtils.isBlank(titleValue)){
            param.put("titleValue",titleValue);
        }
        if (!StringUtils.isBlank(dateValue))
        {
            param.put("dateValue",dateValue);
        }
        if (!StringUtils.isBlank(textValue))
        {
            param.put("textValue",textValue);
        }
        if (!StringUtils.isBlank(textValue))
        {
            param.put("textValue",textValue);
        }
        if (!StringUtils.isBlank(latitude))
        {
            param.put("position.latitude",latitude);
        }
        if (!StringUtils.isBlank(longitude))
        {
            param.put("position.longitude",longitude);
        }
        if (!StringUtils.isBlank(adminDivision))
        {
            param.put("position.adminDivision",adminDivision);
        }
        if (!StringUtils.isBlank(street))
        {
            param.put("position.street",street);
        }
        param.put("task",tasksId);

        NetService.getInstance().postFileWithParam(url, param, addFiles, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                System.out.println(response);
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
            }
        });
    }
}